/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.htbrand.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.Permission;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.pojo.response.ErrorResponseData;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.modular.htbrand.param.HtBrandParam;
import vip.xiaonuo.modular.htbrand.service.HtBrandService;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import vip.xiaonuo.modular.service.MySqlService;
import vip.xiaonuo.sys.modular.emp.param.SysEmpParam;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.param.SysOrgParam;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.param.SysUserParam;
import vip.xiaonuo.sys.modular.user.result.SysUserResult;
import vip.xiaonuo.sys.modular.user.service.SysUserDataScopeService;
import vip.xiaonuo.sys.modular.user.service.SysUserRoleService;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 品牌管理控制器
 *
 * @author yangyuanjiang
 * @date 2022-02-22 14:20:20
 */
@RestController
public class HtBrandController {

    @Resource
    private HtBrandService htBrandService;

    @Resource
    private SysOrgService sysOrgService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysUserDataScopeService sysUserDataScopeService;

    @Resource
    private MySqlService mySqlServicel;

    /**
     * 查询品牌管理
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @GetMapping("/htBrand/page")
    @BusinessLog(title = "品牌管理_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(HtBrandParam htBrandParam) {
        return new SuccessResponseData(htBrandService.page(htBrandParam));
    }

    /**
     * 添加品牌管理
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @PostMapping("/htBrand/add")
    @BusinessLog(title = "品牌管理_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated(HtBrandParam.add.class) HtBrandParam htBrandParam) {
        /** 检查手机是否重复，检查品牌名称是否重复 */
        Object viliName = mySqlServicel.getObjectBySql(" select id from ht_brand where brandname = '"+htBrandParam.getBrandname().trim()+"' limit 0,1");
        if(viliName!=null){
            return new ErrorResponseData(ResponseData.DEFAULT_ERROR_CODE,"品牌名称重复！");
        }
        Object viliPhone = mySqlServicel.getObjectBySql(" select id from ht_brand where phone = '"+htBrandParam.getPhone().trim()+"' limit 0,1");
        if(viliPhone!=null){
            return new ErrorResponseData(ResponseData.DEFAULT_ERROR_CODE,"手机号重复！");
        }
        Object viliUserName = mySqlServicel.getObjectBySql(" select id from ht_brand where username = '"+htBrandParam.getPhone().trim()+"' limit 0,1");
        if(viliUserName!=null){
            return new ErrorResponseData(ResponseData.DEFAULT_ERROR_CODE,"账号重复！");
        }
        /** 往机构中写一条机构数据 */
        SysOrgParam sysOrgParam = new SysOrgParam();
        String maxCode = String.valueOf(mySqlServicel.getObjectBySql(" select max(code)+1 from sys_org where pid = 1 "));
        sysOrgParam.setCode(maxCode);//编号获取最大的编号
        sysOrgParam.setPid(1l);//品牌商上级PID默认为1
        sysOrgParam.setName(htBrandParam.getBrandname()+"(品牌)");
        String maxId = String.valueOf(mySqlServicel.getObjectBySql(" select max(id)+1 from sys_org where pid = 1 "));
        sysOrgParam.setId(Long.parseLong(maxId));
        String maxSort = String.valueOf(mySqlServicel.getObjectBySql(" select max(sort)+1 from sys_org where pid = 1 "));
        sysOrgParam.setSort(1);
        sysOrgParam.setRemark("system");
        sysOrgParam.setIsSystem(1);//此参数表示系统调用，能通过权限验证
        sysOrgService.add(sysOrgParam);
        /** 登录账号信息 */
        SysUserParam sysUserParam = new SysUserParam();
        sysUserParam.setName(htBrandParam.getBrandname());
        sysUserParam.setAccount(htBrandParam.getUsername());
        sysUserParam.setPhone(htBrandParam.getPhone());
        sysUserParam.setNickName(htBrandParam.getBrandname());
        sysUserParam.setSex(1);
        sysUserParam.setIsSystem(1);
        SysEmpParam sysEmpParam = new SysEmpParam();
        sysEmpParam.setOrgId(sysOrgParam.getId());
        sysEmpParam.setId(sysUserParam.getId());
        sysEmpParam.setOrgName(sysOrgParam.getName());
        List<Dict> extIds = new ArrayList<Dict>();
        Dict dict = new Dict();
        dict.put("posId",1265476890672672787l);
        dict.put("orgId",sysOrgParam.getId());
        extIds.add(dict);
        sysEmpParam.setExtIds(extIds);
        List<Long> posIdList = new ArrayList<Long>();
        posIdList.add(1265476890672672787l);
        sysEmpParam.setPosIdList(posIdList);
        sysUserParam.setSysEmpParam(sysEmpParam);
        sysUserService.add(sysUserParam);
        String userId = String.valueOf(mySqlServicel.getObjectBySql(" select id from sys_user where account = '"+htBrandParam.getUsername()+"' "));
        sysUserParam.setId(Long.parseLong(userId));
        /** 写入品牌表数据，并关联机构ID和登录账号ID */
        htBrandParam.setPublicOrgId(sysOrgParam.getId());
        htBrandParam.setPublicOrgName(htBrandParam.getBrandname()+"(品牌)");
        htBrandParam.setPublicUserId(sysUserParam.getId());
        htBrandParam.setPublicUserName(sysUserParam.getName());
        htBrandService.add(htBrandParam);
        /** 全部写入成功后，授权用户角色以及权限 */
        List<Long> grantRoleIdList = new ArrayList<Long>();
        String userRoleId = String.valueOf(mySqlServicel.getObjectBySql(" select id from sys_role where name = '品牌商' "));
        grantRoleIdList.add(Long.parseLong(userRoleId));
        List<Long> grantOrgIdList = new ArrayList<Long>();
        String userOrgId = String.valueOf(mySqlServicel.getObjectBySql(" select id from sys_org where pid = '"+sysOrgParam.getId()+"' "));
        if(userOrgId!=null){
            grantOrgIdList.add(Long.parseLong(userRoleId));
            userOrgId = String.valueOf(mySqlServicel.getObjectBySql(" select id from sys_org where pid = '"+sysOrgParam.getId()+"' "));
        }
        sysUserParam.setGrantOrgIdList(grantOrgIdList);
        sysUserParam.setGrantRoleIdList(grantRoleIdList);
        sysUserDataScopeService.grantData(sysUserParam);
        sysUserRoleService.grantRole(sysUserParam);
        /** 设置密码 */
        sysUserParam.setPassword("1oo111");
        sysUserParam.setNewPassword(htBrandParam.getPassword());
        sysUserService.updateSysPwd(sysUserParam);
        return new SuccessResponseData();
    }

    /**
     * 删除品牌管理，可批量删除
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @PostMapping("/htBrand/delete")
    @BusinessLog(title = "品牌管理_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(HtBrandParam.delete.class) List<HtBrandParam> htBrandParamList) {
            htBrandService.delete(htBrandParamList);
        return new SuccessResponseData();
    }

    /**
     * 编辑品牌管理
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @PostMapping("/htBrand/edit")
    @BusinessLog(title = "品牌管理_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData edit(@RequestBody @Validated(HtBrandParam.edit.class) HtBrandParam htBrandParam) {
        /** 检查手机是否重复，检查品牌名称是否重复 */
        Object viliName = mySqlServicel.getObjectBySql(" select id from ht_brand where id != '"+htBrandParam.getId()+"' and brandname = '"+htBrandParam.getBrandname().trim()+"' limit 0,1");
        if(viliName!=null){
            return new ErrorResponseData(ResponseData.DEFAULT_ERROR_CODE,"品牌名称重复！");
        }
        Object viliPhone = mySqlServicel.getObjectBySql(" select id from ht_brand where id != '"+htBrandParam.getId()+"' and phone = '"+htBrandParam.getPhone().trim()+"' limit 0,1");
        if(viliPhone!=null){
            return new ErrorResponseData(ResponseData.DEFAULT_ERROR_CODE,"手机号重复！");
        }
        Object viliUserName = mySqlServicel.getObjectBySql(" select id from ht_brand where id != '"+htBrandParam.getId()+"' and username = '"+htBrandParam.getPhone().trim()+"' limit 0,1");
        if(viliUserName!=null){
            return new ErrorResponseData(ResponseData.DEFAULT_ERROR_CODE,"账号重复！");
        }
        /** 修改机构信息 */
        String orgId = String.valueOf(mySqlServicel.getObjectBySql(" select public_org_id from ht_brand where id = '"+htBrandParam.getId()+"' "));
        SysOrgParam sysOrgParam = new SysOrgParam();
        sysOrgParam.setId(Long.parseLong(orgId));
        SysOrg sysOrg = sysOrgService.detail(sysOrgParam);
        BeanUtil.copyProperties(sysOrg, sysOrgParam);
        sysOrgParam.setName(htBrandParam.getBrandname()+"(品牌)");
        sysOrgParam.setRemark("system");//此参数表示系统调用，能通过权限验证
        sysOrgParam.setIsSystem(1);//此参数表示系统调用，能通过权限验证
        sysOrgService.edit(sysOrgParam);
        /** 修改登录账号信息 */
        String userId = String.valueOf(mySqlServicel.getObjectBySql(" select public_user_id from ht_brand where id = '"+htBrandParam.getId()+"' "));
        SysUserParam sysUserParam = new SysUserParam();
        sysUserParam.setId(Long.parseLong(userId));
        SysUserResult sysUser = sysUserService.detail(sysUserParam);
        BeanUtil.copyProperties(sysUser, sysUserParam);
        sysUserParam.setName(htBrandParam.getBrandname());
        sysUserParam.setAccount(htBrandParam.getUsername());
        sysUserParam.setPhone(htBrandParam.getPhone());
        sysUserParam.setNickName(htBrandParam.getBrandname());
        sysUserParam.setSex(1);
        sysUserParam.setIsSystem(1);//此参数表示系统调用，能通过权限验证
        SysEmpParam sysEmpParam = new SysEmpParam();
        sysEmpParam.setOrgId(sysOrgParam.getId());
        sysEmpParam.setId(sysUserParam.getId());
        sysEmpParam.setOrgName(sysOrgParam.getName());
        List<Dict> extIds = new ArrayList<Dict>();
        Dict dict = new Dict();
        dict.put("posId",1265476890672672787l);
        dict.put("orgId",sysOrgParam.getId());
        extIds.add(dict);
        sysEmpParam.setExtIds(extIds);
        List<Long> posIdList = new ArrayList<Long>();
        posIdList.add(1265476890672672787l);
        sysEmpParam.setPosIdList(posIdList);
        sysUserParam.setSysEmpParam(sysEmpParam);
        sysUserService.edit(sysUserParam);
        /** 修改品牌信息 */
        htBrandService.edit(htBrandParam);
        /** 设置密码 */
        sysUserParam.setNewPassword(htBrandParam.getPassword());
        sysUserService.updateSysPwd(sysUserParam);
        return new SuccessResponseData();
    }

    /**
     * 重置密码
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @PostMapping("/htBrand/resetPwd")
    @BusinessLog(title = "系统用户_重置密码", opType = LogAnnotionOpTypeEnum.UPDATE)
    public ResponseData resetPwd(@Validated(HtBrandParam.detail.class) HtBrandParam htBrandParam) {
        mySqlServicel.updateSql("update bt_brand set password = '123456' where id = '"+htBrandParam.getId()+"'");
        String userId = String.valueOf(mySqlServicel.getObjectBySql(" select public_user_id from ht_brand where id = '"+htBrandParam.getId()+"' "));
        SysUserParam sysUserParam = new SysUserParam();
        sysUserParam.setId(Long.parseLong(userId));
        sysUserParam.setNewPassword("123456");
        sysUserService.updateSysPwd(sysUserParam);
        return new SuccessResponseData();
    }

    /**
     * 查看品牌管理
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @GetMapping("/htBrand/detail")
    @BusinessLog(title = "品牌管理_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(@Validated(HtBrandParam.detail.class) HtBrandParam htBrandParam) {
        return new SuccessResponseData(htBrandService.detail(htBrandParam));
    }

    /**
     * 品牌管理列表
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @GetMapping("/htBrand/list")
    @BusinessLog(title = "品牌管理_列表", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(HtBrandParam htBrandParam) {
        return new SuccessResponseData(htBrandService.list(htBrandParam));
    }

    /**
     * 导出系统用户
     *
     * @author yangyuanjiang
     * @date 2022-02-22 14:20:20
     */
    @Permission
    @GetMapping("/htBrand/export")
    @BusinessLog(title = "品牌管理_导出", opType = LogAnnotionOpTypeEnum.EXPORT)
    public void export(HtBrandParam htBrandParam) {
        htBrandService.export(htBrandParam);
    }

}
